package com.cg.controller;

import com.cg.service.NumService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @ClassName TestController
 * @Description TODO
 * @Author CG
 * @Date 2024/1/3 13:58
 **/
@RestController
@RequestMapping("/test")
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public class TestController {


    @Resource
    private NumService numService;

    /**
     * 生成条形码测试
     */
    @GetMapping("/barCode")
    public String barCode(String cardNum){
        return numService.createBarCode(cardNum);
    }

    /**
     * 生成二维码测试
     */
    @GetMapping("/code")
    public String code(String cardNum){
        return numService.createCode(cardNum);
    }


    private static Integer arrangeId = 18;//排班id
    private static Integer count = 14;//余号数
    private static Integer index = 0;//序号
    private final Logger logger = LoggerFactory.getLogger(TestController.class);


    //redissonClient
    @Resource
    private RedissonClient redissonClient;

    /**
     * 预约
     * @return
     */
    @GetMapping("/getCount")
    public String getCount(){
        RLock rLock = redissonClient.getLock(arrangeId.toString());
        try {
            Boolean result = rLock.tryLock();
            if(result){
                if(count <= 0){
                    logger.info("没有余号");
                    return "没有余号";
                }
                count--;
                index++;
                logger.info("预约到号，余号数："+count+"，序号:"+index);
                return "预约成功";
            }
            //没有获取到资源
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(rLock != null && rLock.isLocked()){
                if(rLock.isHeldByCurrentThread()){
                    rLock.unlock();
                }
            }
        }
        return "预约失败";
    }
}
